package com.yunxi.service.dubboService.impl.otd;

import com.alibaba.fastjson.JSONObject;
import com.yunxi.bizToHub.pojo.EaiLogs;
import com.yunxi.bizToHub.pojo.OtdModelVO;
import com.yunxi.bizToHub.pojo.OtdOptionVO;
import com.yunxi.bizToHub.pojo.WeekPlanDataVO;
import com.yunxi.bizToHub.pojo.WeekPlanVO;
import com.yunxi.bizToHub.service.EaiLogBizToHubService;
import com.yunxi.core.util.DateUtil;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.model.otd.OtdIfProducePlan;
import com.yunxi.model.otd.OtdWeekPlan;
import com.yunxi.order.pojo.CustomerOrderMatchVO;
import com.yunxi.otd.pojo.OtdIfProducePlanVO;
import com.yunxi.otd.service.OtdWeekPlanAuditDubboService;
import com.yunxi.rocketMq.producer.OtdWeekPlanProducer;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.OrderVehicleService;
import com.yunxi.service.localService.VehicleProductViewService;
import com.yunxi.service.localService.otd.OtdIfProducePlanService;
import com.yunxi.service.localService.otd.OtdWeekPlanService;
import com.yunxi.vehicle.pojo.VehicleProductViewVO;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 周度需求计划审批 服务实现类 weekPlan.state 1新建 2提交 3下发 4驳回 upload state 1未释放 2生产待审核 3驳回 4已下发
 * </p>
 *
 * @author XUQI
 * @since 2019-05-09
 */

public class OtdWeekPlanAuditDubboServiceImpl implements OtdWeekPlanAuditDubboService {

    private static final Logger logger = LoggerFactory.getLogger(OtdWeekPlanAuditDubboServiceImpl.class);

    @Autowired
    @Qualifier("otdIfProducePlanServiceImpl")
    OtdIfProducePlanService ifPlanService;

    @Autowired
    @Qualifier("otdWeekPlanServiceImpl")
    OtdWeekPlanService weekPlanService;

    @Autowired
    @Qualifier("vehicleProductViewServiceImpl")
    VehicleProductViewService productService;


    @Autowired
    private OtdWeekPlanProducer otdWeekPlanProducer;

    @Autowired
    private EaiLogBizToHubService eaiLogBizToHubServiceImpl;
    @Autowired
    @Qualifier("codeCreateServiceImpl")
    CodeCreateService codeCreateServiceImpl;


    @Autowired
    @Qualifier("orderVehicleServiceImpl")
    OrderVehicleService orderService;

    @Value("${mq.switch}")
    private String mq_switch;

    @Override
    public List<OtdIfProducePlanVO> findIfPlanListByWeek(String year, String month, String week) {
        return ifPlanService.findIfListByWeek(year, month, week);
    }


    @Override
    public ApiResult addIfPlan(OtdIfProducePlanVO planVO, LoginInfo user) {
        VehicleProductViewVO product = productService
                .findProductBySub(planVO.getProduct().getCatalogCode(), planVO.getProduct().getColorCodeIn(),
                        planVO.getProduct().getColorCodeOut());
        OtdIfProducePlan ifPlan = convertBean(planVO);

        ifPlan.setPlanNo(codeCreateServiceImpl.createCode("WPLAN", 5));
        ifPlan.setOrderYear(planVO.getOrderYear());
        ifPlan.setOrderMonth(planVO.getOrderMonth());
        ifPlan.setOrderWeek(planVO.getOrderWeek());
        ifPlan.setExpectedDemandDate(planVO.getExpectedDemandDate());
        ifPlan.setInterfaceType("A");//接口类型：新增
        ifPlan.setProductCode(product.getProductCode());
        ifPlan.setVehicleCode(product.getSeriesCode());//车系
        ifPlan.setOrderType("国内");//订单类型
        ifPlan.setCarModel(product.getCatalogCode());//变量车型（15位物料码）
        ifPlan.setCarName(generateCarName(product,ifPlan.getCustomPackCode()));// 整车描述
        ifPlan.setCustomPackCode(ifPlan.getCustomPackCode());
        ifPlan.setZzpack(product.getBatteryPackCode());//电池包
        ifPlan.setCarLimitState("0");//整车下线限制类型
        ifPlan.setProjectCarNo("");// 630没有 匹配项目车
        ifPlan.setWorks("AP21");// 工厂
        ifPlan.setSapState("N");
        ifPlan.setCreateBy(user.getUserCode());
        ifPlan.setUpdateBy(user.getUserCode());
        ifPlanService.save(ifPlan);
        return ResponseUtil.ok();
    }

    @Override
    public ApiResult removeIfPlan(String ifPlanId) {
        ifPlanService.removeById(ifPlanId);
        return ResponseUtil.ok();
    }


    @Override
    public ApiResult modifyIfPlan(OtdIfProducePlanVO planVO, LoginInfo user) {
        OtdIfProducePlan ifPlan = new OtdIfProducePlan();
        BeanUtils.copyProperties(planVO,ifPlan);
        ifPlan.setUpdateBy(user.getUserCode());
        if(!ifPlanService.updateById(ifPlan)){
            return ResponseUtil.fail(-1,"请查询后重试！");
        }
        return ResponseUtil.ok();
    }

    /**
     * 下发周生产计划
     * @param weekPlanId id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult sendWeekPlan(String weekPlanId) {
        logger.info("周计划接口开始...");
        // 周生产订单单车集合
        List<WeekPlanVO> orders = new ArrayList<>();
        // 选装包
        List<OtdOptionVO> packages = new ArrayList<>();
        // 配置
        List<OtdModelVO> options = new ArrayList<>();

        //查询周计划  修改周计划状态
        OtdWeekPlan weekPlan = weekPlanService.getById(weekPlanId);
        weekPlan.setState("3");//已下发
        weekPlan.setUpdateDate(new Date());
        weekPlanService.updateById(weekPlan);

        logger.info("查询待发送的接口数据...");
        // 查询待发送的接口数据
        List<OtdIfProducePlanVO> dataList = ifPlanService
            .findIfListByWeek(weekPlan.getYear(), weekPlan.getMonth(), weekPlan.getWeek());

        logger.info("查询已匹配零售订单且未配车的 订货单...");
        //已匹配零售订单且未配车的 订货单
        Map<String, List<String>> map = createWaitMatchOrder();

        logger.info("创建生产订单单车...");
        // 创建生产订单单车
        Map<String, String> packageNoMap = new HashMap<>();
        packageNoMap.put("","10000");
        int initPackageNo = 10000;
        for (OtdIfProducePlanVO ifPlan : dataList) {
            //通过批售单匹配客户订单
            if(!CollectionUtils.isEmpty(map)){
                String productCustomCode = ifPlan.getProductCode() + (StringUtils.isEmpty(ifPlan.getCustomPackCode()) ? ""
                    : ifPlan.getCustomPackCode());
                List<String> customerList = map.get(productCustomCode);
                if(!CollectionUtils.isEmpty(customerList)){
                    ifPlan.setCusOrderNo(customerList.get(0));
                    customerList.remove(0);
                    map.put(productCustomCode, customerList);
                }
            }

            int packageNo;
            //选装包
            String packageCode = StringUtils.isEmpty(ifPlan.getCustomPackCode()) ? "" : ifPlan.getCustomPackCode();
            // 选装包、选装包配置
            if (packageNoMap.get(packageCode) == null) {
                initPackageNo += 100;
                packageNo = initPackageNo;
                packageNoMap.put(packageCode, String.valueOf(packageNo));
                //选装包集合
                String[] packageCodes = packageCode.split(",");
                for (String code : packageCodes) {
                    OtdOptionVO packageVO = new OtdOptionVO();
                    packageVO.setPackage_no(String.valueOf(packageNo));
                    packageVO.setOption_code(code);
                    packageVO.setCar_model(ifPlan.getProduct().getCatalogCode());
                    //packageVO.setCar_model("AM861BFMCHL19B0");
                    packages.add(packageVO);
                }

                // 选装包配置
                List<OtdModelVO> modelVOS = productService
                    .findConfigByCustomPackCode(ifPlan.getProduct().getCatalogCode(), ifPlan.getCustomPackCode(),
                        String.valueOf(packageNo));
             /*   for (int i = 0; i < modelVOS.size(); i++) {
                    OtdModelVO otdModelVO =  modelVOS.get(i);
                    otdModelVO.setCar_model("AM861BFMCHL19B0");
                }*/
                options.addAll(modelVOS);

            } else {
                packageNo = Integer.parseInt(packageNoMap.get(packageCode));
            }
            // 创建生产订单接口数据
            orders.add(createInterfacePlanData(ifPlan, String.valueOf(packageNo)));

            OtdIfProducePlan ifProducePlan= convertBean(ifPlan);
            ifProducePlan.setSapState("W");//待反馈
            if(!ifPlanService.updateById(ifProducePlan)){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseUtil.fail(-1,"该周已无法释放！");
            }

        }
        WeekPlanDataVO dataVO = new WeekPlanDataVO();
        dataVO.setOptions(packages);
        dataVO.setPackages(options);
        dataVO.setOrders(orders);
        String json = JSONObject.toJSONString(dataVO);
        logger.info("周计划接口下发，JSON:\n" + json);
        EaiLogs eaiLogs = new EaiLogs();
        eaiLogs.setPmsEaiContent(JSONObject.toJSONString(dataVO));
        eaiLogBizToHubServiceImpl.saveWeekPlanEaiLog(eaiLogs);
        if (mq_switch.equals("true")){
            otdWeekPlanProducer.sendMessage(JSONObject.toJSONString(dataVO));
        }
        return ResponseUtil.ok();

    }

    /**
     * 创建生产订单接口数据
     *
     * @param ifPlan ifPlan
     * @return WeekPlanVO
     */
    public static WeekPlanVO createInterfacePlanData(OtdIfProducePlanVO ifPlan, String packageNo) {
        WeekPlanVO data = new WeekPlanVO();
        data.setCar_limit_reason(ifPlan.getCarLimitReason());
        data.setCar_limit_state(ifPlan.getCarLimitState());
        //data.setCar_model("AM861BFMCHL19B0");
        data.setCar_model(ifPlan.getCarModel());
        data.setCar_name(ifPlan.getCarName());
        data.setDealer_no(ifPlan.getDealerNo());
        data.setIndicator(ifPlan.getInterfaceType());
        data.setLock_flag(ifPlan.getLockFlag());
//        data.setOrder_date(DateUtil.format(ifPlan.getExpectedDemandDate(), "yyyyMMdd"));//排程需求日期
        data.setOrder_date(DateUtil.format(new Date(),"yyyyMMdd"));
        data.setOrder_no(ifPlan.getCusOrderNo());//客户订单号
        if (ifPlan.getRequestDate() != null) {
            data.setRequest_date(DateUtil.format(ifPlan.getRequestDate(), "yyyyMMdd"));//客户需求日期
        } else {
            data.setRequest_date(DateUtil.format(ifPlan.getExpectedDemandDate(), "yyyyMMdd"));//排程需求日期
        }
        data.setOrder_type(ifPlan.getOrderType());
        data.setOrder_date(DateUtil.format(ifPlan.getExpectedDemandDate(), "yyyyMMdd"));
        data.setPlanno(ifPlan.getPlanNo());
        data.setQty("1");
        data.setPriority(ifPlan.getPriority());
        data.setProject_flag("");//项目用车编号 630为空
        data.setVehicle_code(ifPlan.getVehicleCode());
        data.setWerks(ifPlan.getWorks());
        data.setZextcolor(ifPlan.getProduct().getColorCodeOut());
        data.setZinttrim(ifPlan.getProduct().getColorCodeIn());
        data.setPackage_no(packageNo);// 对应配置list
        return data;
    }


    /**
     * VO TO BEAN
     * @param planVO
     * @return
     */
    private OtdIfProducePlan convertBean (OtdIfProducePlanVO planVO){
        OtdIfProducePlan ifPlan = new OtdIfProducePlan();
        BeanUtils.copyProperties(planVO, ifPlan);
        return ifPlan;
    }


    /**
     * 生成整车描述
     * @param product
     * @param customPackCode
     */
    private String generateCarName(VehicleProductViewVO product, String customPackCode) {
//        整车描述：861（工程车型中文描述）+直客版（基础车型中文描述）+年型(对应的特征族MY_  )+市场销售(对应的特征族MS_  国别)+内
//        饰风格（对应的特征族NNN）+外饰风格（对应的特征族NNN）+电池容量（对应的特征族PWA）+天窗（对应的特征族UWA）+选装包个数（统计选装包个数）
        int customPackNum = 0;
        if(!StringUtils.isEmpty(customPackCode)){
            customPackNum=customPackCode.split(",").length;
        }
        return product.getModelName()+product.getCatalogName()+product.getYearName()+product.getCountryName()+product.getColorNameIn()
                +product.getColorNameOut()+product.getBatteryPackName()+productService.findDormerNameByCatalog(product.getCatalogCode())
                +customPackNum;
    }


    /**
     * 已匹配零售订单且未配车的 订货单
     * @return
     */
    private Map<String,List<String>> createWaitMatchOrder(){
        // key:产品编号加选装包  value:List<客户订单号>
        Map<String, List<String>> map = new HashMap<>();

        //查询已匹配零售订单且未配车的 订货单
        List<CustomerOrderMatchVO> orderList = orderService.queryCustomerOrderMatchVO();
        if(CollectionUtils.isEmpty(orderList)){
            return null;
        }
        orderList.forEach(data -> {
            List<String> list = map.get(data.getProductCustomCode());
            if( CollectionUtils.isEmpty(list)){
                list = new ArrayList<>();
            }
            list.add(data.getCustomOrderNo());
            map.put(data.getProductCustomCode(),list);
        });
        return map;
    }
}
